const db = require("../lib/conn_oracle");
// //导入用户生成jwt字符串的包
const JWT = require("../util/JWT")
const path = require("path")

const encryption = require("../util/encryption")
const DateFormat = require("../util/dateFormat")
const loginAndSession = require("../util/loginAndSession")

const { socketTokenCheck , reNewTokenToClint} = require("../util/socketTokenCheck")



exports.loginHtml = (req, res) => {
    const indexPath = path.join(__dirname, '../dist/index.html');
    res.sendFile(indexPath, (err) => {
        if (err) {
            res.status(500).send('无法加载登录页面: ' + err.message);
        }
    });
}

//用户信息
exports.userInfo = async (req,res)=>{
    // console.log(req.headers['x-forwarded-for'] )
    // console.log(req.body)
    let clientIp = req.connection.remoteAddress
    let {username,password} = req.body  
    //查询用户是否存在              
    let usersSql = `select * from c##wxw.vue_xfjcusers
                    where username = :username   
                    `
    //获取用户目录
    let userMenuSql = `
                    select u.personid,u.username,u.realname
                    ,urm.roleid,ram.authorityid,adm.dirid
                    ,adm.is_add,adm.is_update,adm.is_del
                    ,d.title,d.parent,d.path,d.dirlevel
                    ,d.icon,d.componentname,d.reporturl
                    ,d.remark,d.dirname,d.componentpath
                    ,d.cust_type
                    from c##wxw.vue_xfjcusers u
                    inner join c##wxw.vue_xfjcUser_Role_middle urm
                    on u.personid = urm.personid
                    inner join c##wxw.vue_xfjcRole_Authority_middle ram
                    on urm.roleid = ram.roleid
                    inner join c##wxw.vue_xfjcAuthority_Dirs_middle adm
                    on  ram.authorityid = adm.authorityid
                    inner join c##wxw.vue_xfjcDirs d
                    on adm.dirid = d.id
                    where username = :username
                    `
    //获取用户收藏
    let collectSql = `select * from c##wxw.vue_xfjcuser_collect where personid = :PERSONID`
    let datas;
    let loginLogDatas
    let sessionDatas
    //参数1：用户的信息对象，参数2：加密的密钥，参数3：配置对象，可以配置当前的token有效期
    async function fun(){
        let users = await db.search(usersSql,[username])      
        if(users.length === 0){
            //首次登陆添加超级管理员（未完成）
            // if(username === 'admin'){
            //     // console.log(username)
            //     let cps = await checkPs.psToDb(username,password)
            //     // console.log(cps)
            //     cps.resStatus ? res.json({msg:"ok"}) : res.json({msg:"err"}) 
            //     return false                
            // }else{
                res.json({
                    status:0,
                    msg:"用户名或密码错误",
                    datas
                })
            // }               
        }else{
            let isMatch = await encryption.isMatch(password,users[0].PASSWORD) //加密后密码验证
            if(isMatch){
                //登陆成功后，调用JWT.generate方法生成jwt字符串。
                let tokenStr = JWT.generate({
                    username:users[0].USERNAME,
                    personid:users[0].PERSONID
                },"1h")
                //获取token中的有效载荷
                let playload = JWT.verify(tokenStr) 
                //乘以1000（对于JavaScript和Java）是因为这些语言中的时间处理通常以毫秒为单位
                let lastActive = DateFormat.dateFormat(playload.exp*1000)            
                //响应头添加Authorization为token字符串
                res.setHeader('Authorization', tokenStr)
                //获取用户目录
                let userMenu = await db.search(userMenuSql,[username])   
                //获取用户收藏
                let userCollect = await db.search(collectSql,[users[0].PERSONID])  
                 //用户登录日志数据
                loginLogDatas = [users[0].PERSONID,clientIp,'LOGIN','SUCCESS']
                //用户session  personid_时间戳_客户端ip
                let sessionId = users[0].PERSONID + "_" + Date.now() + "_" + clientIp
                //token加密
                let tokenStrHash = await encryption.hashedToken(tokenStr)  
                //session数据              
                sessionDatas = [sessionId,users[0].PERSONID,tokenStrHash,clientIp,lastActive,1]
                //用户登录日志和session写入数据库
                await loginAndSession.addLogAndSession(loginLogDatas,sessionDatas)
                // 刷新token任务
                socketTokenCheck(tokenStr)                
                //查询会话信息
                let sessionInfo = await loginAndSession.searchSession([users[0].PERSONID,clientIp,lastActive])
                datas = {users,userMenu,userCollect,sessionInfo}
                res.json({
                    status:1,
                    msg:"登陆成功",
                    datas,
                });            
            }else{
                //用户登录日志
                loginLogDatas = [users[0].PERSONID,clientIp,'LOGIN','FAILED']
                loginAndSession.addLog(loginLogDatas)
                res.json({
                    status:0,
                    msg:"用户名或密码错误",
                    datas
                }); 
            }            
        }        
    } 
    fun();
}
